/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Administracion;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.SAVE_DIALOG;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pato
 */
public class Almacen extends javax.swing.JFrame {

    /**
     * Creates new form Almacen
     */
    private static final NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
    PreparedStatement ps;
    ResultSet rs;
    Vector sucursales = new Vector();
    DefaultTableModel dtm;
    public Almacen() {
        initComponents();
        cargarTipos();
        cargarSucursales();
        dtm=(DefaultTableModel) jTable1.getModel();
        jTable1.getColumnModel().getColumn(2).setCellRenderer(new DecimalFormatRenderer());
        jTable1.getColumnModel().getColumn(3).setCellRenderer(new DecimalFormatRenderer());
        jTable1.getColumnModel().getColumn(4).setCellRenderer(new CantidadFormatRenderer());
        cargarDatos();
    }
private void cargarSucursales(){
        try {
            ps=local_connection.getconnect().prepareStatement("select id, nombre from sucursales where activo = 1");
            rs=ps.executeQuery();
            while(rs.next()){
                sucursales.add(rs.getInt("id"));
                preciosCombo.addItem(rs.getString("nombre"));
                stockCombo.addItem(rs.getString("nombre"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Almacen.class.getName()).log(Level.SEVERE, null, ex);
        }
}
    private void cargarDatos(){
        dtm.setRowCount(0);
        String tipo = (tipos.getSelectedIndex()==0)?"":" and productos.tipo ='"+tipos.getSelectedItem()+"' ";
        try {
            ps=local_connection.cn.prepareStatement("select sum(if(cantidad>0,cantidad,0)*preciocompra),sum(if(cantidad>0,cantidad,0)) from productos join stock on stock.id_producto = productos.id_producto where activo = 1"+tipo
            +((stockCombo.getSelectedIndex()==0)?"":" and stock.sucursal="+sucursales.get(stockCombo.getSelectedIndex()-1)));
            rs=ps.executeQuery();
            rs.next();
            cantidadtotal.setText(rs.getString(2));
            costototal.setText(formatter.format(rs.getFloat(1)));
            ps=local_connection.cn.prepareStatement("select productos.id_producto,productos.nombre,preciocompra,precio,sum(if(stock.cantidad>0,stock.cantidad,0)) from productos join stock "
                    + "on productos.id_producto = stock.id_producto  left outer join precios on precios.id_producto = productos.id_producto and precios.cantidad = 1.0 "
                    + "and precios.sucursal = ? "
                    + "where activo = 1"+tipo+((stockCombo.getSelectedIndex()==0)?"":" and stock.sucursal="+sucursales.get(stockCombo.getSelectedIndex()-1))+" group by stock.id_producto");
            ps.setInt(1, (int) sucursales.get(preciosCombo.getSelectedIndex()));
            rs=ps.executeQuery();
            ArrayList<Object[]> data = new ArrayList<>();
            while (rs.next()) {

                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);

            }
            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }

        } 
        catch (SQLException ex) {
            Logger.getLogger(Almacen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void cargarTipos(){
        try {
            tipos.addItem("Todos");
            ps=local_connection.cn.prepareStatement("Select tipo from productos group by tipo");
            rs=ps.executeQuery();
            while(rs.next())
                tipos.addItem(rs.getString(1));
        } catch (SQLException ex) {
            Logger.getLogger(Almacen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
static class DecimalFormatRenderer extends DefaultTableCellRenderer {


        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            // First format the cell value as required
             if(value==null)value=0;
            value = formatter.format((Number) value);

            // And pass it on to parent class 

            return super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
        }
    }
static class CantidadFormatRenderer extends DefaultTableCellRenderer {

    private Font bold = new Font( "Arial",Font.BOLD ,12 );
    private JLabel label = new JLabel();
        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            // First format the cell value as required
            if (isSelected) {                
            this.setBackground( new Color( 50, 153 , 254) );                        
        }
        else
        {
            this.setBackground(Color.white);
        }

           this.setHorizontalAlignment( JLabel.CENTER );
            this.setText( String.valueOf(value) ); 
            if(value==null)value=0.0f;
            this.setForeground( (Float.valueOf(String.valueOf( value))<=0.0f)?Color.RED:new Color(0,150,0) );            
            this.setFont(bold);            
            return this;   
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        stockCombo = new javax.swing.JComboBox();
        tipos = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        exportar = new javax.swing.JButton();
        costototal = new javax.swing.JLabel();
        preciosCombo = new javax.swing.JComboBox();
        movimientos = new javax.swing.JButton();
        cantidadtotal = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel3.setText("Tipo:");

        stockCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos" }));
        stockCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                stockComboPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        tipos.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                tiposPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });
        tipos.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                tiposPropertyChange(evt);
            }
        });

        jLabel1.setText("Cantidad total de productos");

        jLabel5.setText("Stock:");

        jLabel2.setText("Costo total del inventario");

        exportar.setText("Exportar");
        exportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportarActionPerformed(evt);
            }
        });

        costototal.setText("jLabel3");

        preciosCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                preciosComboPopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        movimientos.setText("Movimientos");
        movimientos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                movimientosActionPerformed(evt);
            }
        });

        cantidadtotal.setText("jLabel2");

        jLabel4.setText("Precios:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 505, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(preciosCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(stockCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(tipos, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(movimientos)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(exportar))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(cantidadtotal)
                                        .addGap(148, 148, 148)
                                        .addComponent(costototal)
                                        .addGap(71, 71, 71)))))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(preciosCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(costototal)
                    .addComponent(cantidadtotal, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(stockCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(tipos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(exportar)
                            .addComponent(movimientos))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 2, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nombre", "Costo", "Precio Unitario", "Existencia"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setMaxWidth(50);
            jTable1.getColumnModel().getColumn(2).setMaxWidth(75);
            jTable1.getColumnModel().getColumn(3).setMaxWidth(75);
            jTable1.getColumnModel().getColumn(4).setMaxWidth(70);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1))
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 495, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tiposPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_tiposPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_tiposPropertyChange

    private void movimientosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_movimientosActionPerformed
int row = jTable1.getSelectedRow();
       if(row!=-1) {
           row = jTable1.convertRowIndexToModel(row);
           (new Movimientos(this,true,(int)dtm.getValueAt(row, 0))).setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_movimientosActionPerformed

    private void tiposPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_tiposPopupMenuWillBecomeInvisible
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_tiposPopupMenuWillBecomeInvisible

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
int row = jTable1.getSelectedRow();
       if(row!=-1)
        if (evt.getClickCount() == 2) {
           row = jTable1.convertRowIndexToModel(row);
           (new Movimientos(this,true,(int)dtm.getValueAt(row, 0))).setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void exportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarActionPerformed
 final JFileChooser fileopen = new JFileChooser() {
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
        int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            File file = new File(fileopen.getSelectedFile() + ".xls");
            try {
                new FileWriter(file);
                new ClientesTableExporter(jTable1, file, "Almacen").export();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_exportarActionPerformed

    private void preciosComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_preciosComboPopupMenuWillBecomeInvisible
    cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_preciosComboPopupMenuWillBecomeInvisible

    private void stockComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_stockComboPopupMenuWillBecomeInvisible
cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_stockComboPopupMenuWillBecomeInvisible

    /**
     * @param args the command line arguments
     */
   

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel cantidadtotal;
    private javax.swing.JLabel costototal;
    private javax.swing.JButton exportar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton movimientos;
    private javax.swing.JComboBox preciosCombo;
    private javax.swing.JComboBox stockCombo;
    private javax.swing.JComboBox tipos;
    // End of variables declaration//GEN-END:variables
}
